package com.rabbit.demo.direct;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;


/**
 * @ClassName Consumer
 * @Description TODO
 * @Author 11
 * @Date 2021/7/19 9:41
 * @Version 1.0
 */


@Slf4j
@Service
public class Consumer {

    @Resource
    private AutoRouteService autoRouteService;





    @RabbitListener(
            concurrency = "5-10",
            bindings = @QueueBinding(
                    value = @Queue(value = "CDM-ONE-AGENT-GENERAL", durable = "true"),
                    exchange = @Exchange(value = "CDM-ONE",
                                        durable = "true",
                                        type = "direct",
                                        ignoreDeclarationExceptions = "true"),
                    key = "CDM-ONE-AGENT-GENERAL"
            )
    )
    @RabbitHandler
    public void onMessage(Message message, Channel channel){

        System.out.println(message.getMessageProperties().toString());

        String msg = new String(message.getBody());
        log.info("监听到的消息是： 【{}】",msg);
        /*手动ack*/
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        } catch (IOException e) {
            log.error("手动ack错误，消息内容：【{}】",msg,e);
            e.printStackTrace();
        }


        try {
            log.info("开始处理消息");
            /*处理消息内容逻辑*/
            if (StringUtils.hasLength(msg)){
                log.info("处理消息内容：{}",msg);
                /*路由消息到处理器*/



                MyMessgae mqMsg = null;
                mqMsg = JSON.parseObject(msg, MyMessgae.class);
                log.info("处理消息内容：{}",mqMsg);
                autoRouteService.route(mqMsg);
                log.info("处理完毕！");

            }
        } catch (Exception e) {
            log.error("处理消息内容逻辑错误，消息内容：【{}】",e.getMessage());
            e.printStackTrace();
        }

    }

}
